﻿using System;
using System.IO;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Http;

namespace LeoGemini.Service.Infrastructure.Extension
{
    public static partial class Extensions
    {
        private static MD5 _md5Calculator = MD5.Create();
        private static SHA1 _sha1Calculator = SHA1.Create();
        
        public static string GetMd5(this IFormFile file)
        {
            return ComputeHash(file, _md5Calculator);
        }

        public static string GetSuffix(this IFormFile file)
        {
            return file.FileName.Substring(file.FileName.LastIndexOf('.') + 1).ToLower();
        }

        public static string GetSha1(this IFormFile file)
        {
            return ComputeHash(file, _sha1Calculator);
        }

        public static string SaveTo(this IFormFile file, string path)
        {
            Directory.CreateDirectory(path);
            var absPath = $"{path}\\{file.GetSha1()}.{file.GetSuffix()}";
            
            using (var stream = File.Create(absPath))
            {
                file.CopyTo(stream);
            }

            return absPath;
        }

        private static string ComputeHash(IFormFile file, HashAlgorithm algorithm)
        {
            string hashed = string.Empty;
            using (Stream stream = file.OpenReadStream())
            {
                Byte[] buffer = algorithm.ComputeHash(stream);
                hashed = BitConverter.ToString(buffer).Replace("-", "");
            }

            return hashed;
        }
    }
}